package com.htgd.gardenexpo.controller;

import cn.xuyanwu.spring.file.storage.FileInfo;
import cn.xuyanwu.spring.file.storage.FileStorageService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.amazonaws.services.s3.AmazonS3;
import com.htgd.gardenexpo.entity.*;
import com.htgd.gardenexpo.service.*;
import com.htgd.gardenexpo.utils.*;
import com.htgd.gardenexpo.vo.Person;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.ArrayUtils;
import org.apache.http.Header;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.message.BasicHeader;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author ：hejing
 * @date ：Created in 2021/5/24 9:39
 * @description：基础信息管理
 * @menu 基础信息管理
 * @modified By：`
 * @version: 1.0
 */
@EnableScheduling
@RestController
@RequestMapping("/api/basis")
@Api( tags = "基础信息")
public class BasicInformationManagementController {

    public static SimpleDateFormat sf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    public static SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");

    @Value("${gaode.city}")
    private String city;

    @Value("${gaode.key}")
    private String key;

    @Resource
    private GeBaseDictionaryService geBaseDicyionaryService;

    @Resource
    private GeBaseRoleService geBaseRoleService;

    @Resource
    private GeBaseUserService geBaseUserService;
    @Resource
    private GeBaseRoleMenuService geBaseRoleMenuService;
    @Resource
    private GeBaseMenuService geBaseMenuService;

    @Resource
    private GeBaseUserRoleService geBaseUserRoleService;

    @Resource
    private GeBaseEntryService geBaseEntryService;

    @Resource
    private GeBaseOrgService geBaseOrgService;

    @Resource
    private GeBaseUserRetailService geBaseUserRetailService;

    @Resource
    private GeOuthTokenService geOuthTokenService;

    @Resource
    private GeWeatherService geWeatherService;


    @Autowired
    private FileStorageService fileStorageService;

    @Resource
    private GetAmazonS3Client getAmazonS3Client;

    @Autowired
    private GeBaseDepartService geBaseDepartService;

    @Autowired
    private WxUserService wxUserService;


    @Autowired
    private IGeConWeatherService geConWeatherService;

    private static String pubKey="MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCET6dwdyIc3oqdK9WhnCl0eCiegd2IoKZWYeK2F69LuQ3dbRgI7SrHLxYoE3oOKV1kDilzAbONTJStHkVd-iqZk5TurcItBze2vardjpamXXDLkM9-n1kPz16309RrD2xBvd8hRBy-VQy-JDuONG8GaLc1lgADMCiqYzcK7XIirQIDAQAB";

    @Value("${upload.absolute.url}")
    public String absolute_url;
    @Value("${upload.url}")
    public String upload_url;
    @Value("${local.url}")
    public String local_url;

    @Value("${weather.city}")
    public String weather_city;
    @Value("${weather.key}")
    public String weather_key;
    @Value("${weather.url}")
    public String weather_url;
    @Value("${retail.reg_url}")
    public String regUrl;
    @Value("${retail.delete_url}")
    public String deleteUrl;
    @Value("${retail.branId}")
    public String branId;
    @Value("${retail.trans_query}")
    public String transQuery;
    @Value("${retail.tran_info}")
    public String tranInfo;
    @Value("${retail.gift_rule}")
    public String giftRule;
    @Value("${retail.gift_exchange}")
    public String giftExchange;
    @Value("${retail.vip_coupon}")
    public String vipCoupon;
    @Value("${retail.query_url}")
    public String queryUrl;

    //-------------------------- 用户管理 --------------------------------


    /**
     * 用户登录
     */
    @PostMapping(value = "/userlogin")
    public CommonResult<GeBaseUser> userLogin(String phone,String password) throws InvalidKeySpecException, NoSuchAlgorithmException {
        CommonResult<GeBaseUser> result = new CommonResult<>();
        try {
            List<GeBaseUser> ulist=geBaseUserService.getUserByPhone(phone);
            if (ulist==null||ulist.size()==0){
                result.setCode(300);
                result.setMessage("手机号错误！");
                return  result;
            }
            GeBaseUser geBaseUser=ulist.get(0);
            String pwd=RSAUtils.publicEncrypt(password,RSAUtils.getPublicKey(pubKey));
            if (pwd.equals(geBaseUser.getPassword())){
                result.setCode(200);
                result.setData(geBaseUser);
            }else {
                result.setCode(300);
                result.setMessage("密码错误！");
            }
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(500);
        }
        return result;
    }

    /**
     * 获取用户角色权限
     */
    @GetMapping(value = "/getUserRoleMenu")
    public CommonResult<List<GeBaseMenu>> getUserRoleMenu(int userId){
        CommonResult<List<GeBaseMenu>> result = new CommonResult<>();
        try {
            List<GeBaseUserRole> rlist=geBaseUserRoleService.getUserRoleByUserId(userId);
            String urs="";
            for (GeBaseUserRole geBaseUserRole:rlist){
                urs+=geBaseUserRole.getRoleId()+",";
            }
            if (!urs.equals("")){
                String[] ur=urs.split(",");
                List<GeBaseRoleMenu> mlist=geBaseRoleMenuService.getMenusByRoleIds(ur);
                String menus="";
                for (GeBaseRoleMenu geBaseRoleMenu:mlist){
                    menus+=geBaseRoleMenu.getMenuId()+",";
                }
                if (!menus.equals("")){
                    List<GeBaseMenu> mmlist=geBaseMenuService.getMenusByMenuIds(menus.split(","),0);
                    List<GeBaseMenu> bmlist=node_merge(mmlist,menus,0);
                    result.setData(bmlist);
                    List<GeBaseMenu> gmlist=geBaseMenuService.getMenusByMenuIds(menus.split(","),1);
                    result.setData1(gmlist);
                }
            }
            result.setCode(200);
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(500);
        }
        return result;
    }

    public List<GeBaseMenu> node_merge(List<GeBaseMenu> list,String menus,int parent_id){
        List<GeBaseMenu> geBaseMenuList = new ArrayList<>();
        for (GeBaseMenu geBaseMenu:list){
            if (geBaseMenu.getParentId()==parent_id){
                geBaseMenu.setChildren(node_merge(list,menus,geBaseMenu.getMenuId()));
                if (ArrayUtils.contains(menus.split(","),geBaseMenu.getMenuId().toString())){
                    geBaseMenu.setCheck(true);
                }else {
                    geBaseMenu.setCheck(false);
                }
                geBaseMenuList.add(geBaseMenu);
            }
        }
        return geBaseMenuList;
    }



    /**
     * 新增用户信息
     */
    @PostMapping(value = "/addUserInfo")
    @ApiOperation("新增用户信息")
    public CommonResult<JSONObject> addUserInfo(@RequestBody GeBaseUser geBaseUser) throws InvalidKeySpecException, NoSuchAlgorithmException {
        CommonResult<JSONObject> result=new CommonResult<>();
        try {
            String phone=geBaseUser.getPhone();
            List<GeBaseUser> users=geBaseUserService.getUserByPhone(phone);
            String pwd=geBaseUser.getPassword();
            geBaseUser.setPassword(RSAUtils.publicEncrypt(pwd,RSAUtils.getPublicKey(pubKey)));
            if (users!=null&&users.size()>0){
                geBaseUserService.updateByPhone(geBaseUser);
                if (geBaseUser.getRoleId()!=null){
                    String[] roles=geBaseUser.getRoleId().split(",");
                    for (String role:roles){
                        List<GeBaseUserRole> userRoleByUserId = geBaseUserRoleService.getUserRoleByUserId(users.get(0).getUserId());
                        if(userRoleByUserId!=null&&userRoleByUserId.size()>0){
                            if(role.equals(String.valueOf(userRoleByUserId.get(0).getRoleId()))){
                                break;
                            }else {
                                GeBaseUserRole geBaseUserRole=new GeBaseUserRole();
                                geBaseUserRole.setUserId(users.get(0).getUserId());
                                geBaseUserRole.setRoleId(Integer.parseInt(role));
                                geBaseUserRoleService.update(geBaseUserRole);
                            }
                        }else {
                            GeBaseUserRole geBaseUserRole=new GeBaseUserRole();
                            geBaseUserRole.setUserId(users.get(0).getUserId());
                            geBaseUserRole.setRoleId(Integer.parseInt(role));
                            geBaseUserRoleService.insert(geBaseUserRole);
                        }
                    }
                }
                result.setCode(200);
                result.setMessage("更新成功");
                return result;
            }
            geBaseUserService.insert(geBaseUser);

            if (geBaseUser.getRoleId()!=null){
                String[] roles=geBaseUser.getRoleId().split(",");
                for (String role:roles){
                    GeBaseUserRole geBaseUserRole=new GeBaseUserRole();
                    geBaseUserRole.setUserId(geBaseUser.getUserId());
                    geBaseUserRole.setRoleId(Integer.parseInt(role));
                    geBaseUserRoleService.insert(geBaseUserRole);
                }
            }
//            addRetailinfo(geBaseUser);
            result.setCode(200);
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(500);
        }
        return result;
    }
    /**
     * 上传图片
     */
//    @PostMapping(value = "/uploadPhoto")
//    public String uploadPhoto(@RequestParam(value = "file") MultipartFile file,HttpServletResponse response){
//        String type = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
//        if(type.equals(".svg")){
//            //使用指定的存储平台
//            FileInfo fileInfo=fileStorageService.of(file)
//                    .setPlatform("aws-s3-1")
////                .setSaveFilename(sdf.format(new Date())+"/"+file.getOriginalFilename())
//                    .upload();
//            return upload_url+fileInfo.getFilename();
//        }else {
//            //使用指定的存储平台
//            FileInfo fileInfo=fileStorageService.of(file)
//                    .setPlatform("aws-s3-1")
//                    .image(img -> img.scale(0.4f))
////                .setSaveFilename(sdf.format(new Date())+"/"+file.getOriginalFilename())
//                    .upload();
//            return upload_url+fileInfo.getFilename();
//        }
//
//    }
    /**
     * 上传图片
     */
    @PostMapping(value = "/uploadPhotoApp")
    public String uploadPhotoWx(@RequestParam(value = "file") MultipartFile file){

        //使用指定的存储平台
        FileInfo fileInfo=fileStorageService.of(file)
                .setPlatform("aws-s3-1")
                .image(img -> img.scale(0.4f))
//                .setSaveFilename(sdf.format(new Date())+"/"+file.getOriginalFilename())
                .upload();
        return upload_url+fileInfo.getFilename();
    }
    /**
     * 上传人脸图片
     */
    @PostMapping(value = "/uploadFacePhoto")
    public String uploadFacePhoto(@RequestParam(value = "file") MultipartFile file){
        double scale=1.0d;
        if (file.getSize()-(300*1024)>0){
//            System.out.println(file.getSize());
            scale=(300*1024f) / (file.getSize());
        }
        //使用指定的存储平台
        if (scale!=1.0d){
            double finalScale = scale;
            FileInfo fileInfo=fileStorageService.of(file)
                    .setPlatform("aws-s3-1")
                    .image(img -> img.scale(finalScale))
                    .setSaveFilename("face/"+System.currentTimeMillis()+file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")))
//                    .image(img -> img.size(200,200))
                    .upload();
            return upload_url+fileInfo.getFilename();
        }else {
            FileInfo fileInfo=fileStorageService.of(file)
                    .setPlatform("aws-s3-1")
                    .setSaveFilename("face/"+System.currentTimeMillis()+file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")))
                    .upload();
            return upload_url+fileInfo.getFilename();
        }

    }
    /**
     * 上传人脸图片
     */
    @PostMapping(value = "/uploadFacePhotoWx")
    public String uploadFacePhotoWx(@RequestParam(value = "file") MultipartFile file){
        double scale=1.0d;
        if (file.getSize()-(300*1024)>0){
//            System.out.println(file.getSize());
            scale=(300*1024f) / (file.getSize());
        }
        //使用指定的存储平台
        if (scale!=1.0d){
            double finalScale = scale;
            FileInfo fileInfo=fileStorageService.of(file)
                    .setPlatform("aws-s3-1")
                    .image(img -> img.scale(finalScale))
                    .setSaveFilename("face/"+System.currentTimeMillis()+file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")))
//                    .image(img -> img.size(200,200))
                    .upload();
            return upload_url+fileInfo.getFilename();
        }else {
            FileInfo fileInfo=fileStorageService.of(file)
                    .setPlatform("aws-s3-1")
                    .setSaveFilename("face/"+System.currentTimeMillis()+file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")))
                    .upload();
            return upload_url+fileInfo.getFilename();
        }

    }
    /**
     * 上传人脸图片
     */
    @PostMapping(value = "/uploadFacePhotoApp")
    public String uploadFacePhotoApp(@RequestParam(value = "file") MultipartFile file){
        double scale=1.0d;
        if (file.getSize()-(300*1024)>0){
//            System.out.println(file.getSize());
            scale=(300*1024f) / (file.getSize());
        }
        //使用指定的存储平台
        if (scale!=1.0d){
            double finalScale = scale;
            FileInfo fileInfo=fileStorageService.of(file)
                    .setPlatform("aws-s3-1")
                    .image(img -> img.scale(finalScale))
                    .setSaveFilename("face/"+System.currentTimeMillis()+file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")))
//                    .image(img -> img.size(200,200))
                    .upload();
            return upload_url+fileInfo.getFilename();
        }else {
            FileInfo fileInfo=fileStorageService.of(file)
                    .setPlatform("aws-s3-1")
                    .setSaveFilename("face/"+System.currentTimeMillis()+file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")))
                    .upload();
            return upload_url+fileInfo.getFilename();
        }

    }

   /* *//**
     * 上传图片
     */
//    @PostMapping(value = "/uploadPhoto")
//    public PutObjectResult uploadPhoto(@RequestParam(value = "file") MultipartFile file) throws IOException {
//        String fileName = file.getOriginalFilename();
//        File toFile = null;
//        String prefix=fileName.substring(fileName.lastIndexOf("."));
//        String filename=System.currentTimeMillis()+prefix;
//        if (file.equals("") || file.getSize() <= 0) {
//            file = null;
//        } else {
//            InputStream ins = null;
//            ins = file.getInputStream();
//            toFile = new File(filename);
//            inputStreamToFile(ins, toFile);
//            ins.close();
//        }
//        PutObjectResult result=getAmazonS3Client.putObject(filename,toFile);
//        toFile.delete();
//        return result;
//    }

    @PostMapping(value = "/uploadPhoto")
    @ApiOperation("上传文件")
    public String uploadPhoto(@RequestParam(value = "file") MultipartFile file) throws IOException {
        if (file.isEmpty()) {
            System.out.println("文件为空");
        }

        BufferedImage image = ImageIO.read(file.getInputStream());
        int width = 0 ;
        int height = 0;
        if (image != null) {
            width = image.getWidth();
            height = image.getHeight();
        }

        String fileName = file.getOriginalFilename();  // 文件名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));  // 后缀名
        String filePath = absolute_url; // 上传后的路径
        fileName = UUID.randomUUID() + "@" + width +"@"+ height +"@"+ suffixName; // 新文件名
        File dest = new File(filePath + fileName);
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return local_url+"upload/"+fileName;
    }
    //获取流文件
    private static void inputStreamToFile(InputStream ins, File file) {
        try {
            OutputStream os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @GetMapping("/delete")
    public void delete(String path){
        AmazonS3 amazonS3=getAmazonS3Client.getClient();
        try {
            amazonS3.deleteObject("xzybyceshi","s3/60c4659319162d4d1c86bbe6.PNG");
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 上传图片
     */
   /* @PostMapping(value = "/uploadUserPhoto")
    public String uploadUserPhoto(@RequestParam(value = "file") MultipartFile file){
        if (file.isEmpty()) {
            System.out.println("文件为空");
        }
        String fileName = file.getOriginalFilename();  // 文件名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));  // 后缀名
        String filePath = absolute_url; // 上传后的路径
        fileName = UUID.randomUUID() + suffixName; // 新文件名
        File dest = new File(filePath + fileName);
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return local_url+"upload/"+fileName;
    }*/


    /**
     * 编辑用户信息
     */
    @PostMapping(value = "/editUserInfo")
    @SecurityParameter
    @Transactional
    public CommonResult<JSONObject> editUserInfo(@RequestBody GeBaseUser geBaseUser) throws InvalidKeySpecException, NoSuchAlgorithmException {
        CommonResult<JSONObject> result=new CommonResult<>();
        try {
            GeBaseUser user=geBaseUserService.queryById(geBaseUser.getUserId());
            if (geBaseUser.getPhone()!=null){
                String phone=user.getPhone();
                if (!phone.equals(geBaseUser.getPhone())){
                    List<GeBaseUser> users=geBaseUserService.getUserByPhone(geBaseUser.getPhone());
                    if (users!=null&&users.size()>0){
                        result.setCode(300);
                        result.setMessage("手机号重复");
                        return result;
                    }
                }
            }
           if (geBaseUser.getPassword()!=null&&(user.getPassword()==null||!user.getPassword().equals(geBaseUser.getPassword()))){
               String pwd=geBaseUser.getPassword();
               geBaseUser.setPassword(RSAUtils.publicEncrypt(pwd,RSAUtils.getPublicKey(pubKey)));
           }
           if (geBaseUser.getIdCard()!=null&&(user.getIdCard()==null||!user.getIdCard().equals(geBaseUser.getIdCard()))){
               String idcard=geBaseUser.getIdCard();
               geBaseUser.setIdCard(RSAUtils.publicEncrypt(idcard,RSAUtils.getPublicKey(pubKey)));
           }
            geBaseUserService.update(geBaseUser);
//           //启用停用
//            if(geBaseUser.getDelFlag()!=null){
//                if(geBaseUser.getDelFlag()==0){
//                    carbonBackTask.startUser(user.getPhone());
//                }else {
//                    carbonBackTask.stopUser(user.getPhone());
//                }
//            }
            if (geBaseUser.getRoleId()!=null&&!geBaseUser.getRoleId().equals("")){
                geBaseUserRoleService.deleteById(geBaseUser.getUserId());
                String[] roles=geBaseUser.getRoleId().split(",");
                for (String role:roles){
                    GeBaseUserRole geBaseUserRole=new GeBaseUserRole();
                    geBaseUserRole.setUserId(geBaseUser.getUserId());
                    geBaseUserRole.setRoleId(Integer.parseInt(role));
                    geBaseUserRoleService.insert(geBaseUserRole);
                }
            }
            result.setCode(200);
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(500);
        }

        return result;
    }

    /**
     * 编辑用户信息
     */
    @PostMapping(value = "/editUserInfoWx")
    @SecurityParameter
    public CommonResult<JSONObject> editUserInfoWx(@RequestBody GeBaseUser geBaseUser) throws InvalidKeySpecException, NoSuchAlgorithmException {
        CommonResult<JSONObject> result=new CommonResult<>();
        try {
            GeBaseUser user=geBaseUserService.queryById(geBaseUser.getUserId());
            if (geBaseUser.getPhone()!=null){
                String phone=user.getPhone();
                if (!phone.equals(geBaseUser.getPhone())){
                    List<GeBaseUser> users=geBaseUserService.getUserByPhone(geBaseUser.getPhone());
                    if (users!=null&&users.size()>0){
                        result.setCode(300);
                        result.setMessage("手机号重复");
                        return result;
                    }
                }
            }
           if (geBaseUser.getPassword()!=null&&(user.getPassword()==null||!user.getPassword().equals(geBaseUser.getPassword()))){
               String pwd=geBaseUser.getPassword();
               geBaseUser.setPassword(RSAUtils.publicEncrypt(pwd,RSAUtils.getPublicKey(pubKey)));
           }
           if (geBaseUser.getIdCard()!=null&&(user.getIdCard()==null||!user.getIdCard().equals(geBaseUser.getIdCard()))){
               String idcard=geBaseUser.getIdCard();
               geBaseUser.setIdCard(RSAUtils.publicEncrypt(idcard,RSAUtils.getPublicKey(pubKey)));
           }
            geBaseUserService.update(geBaseUser);
            if (geBaseUser.getRoleId()!=null&&!geBaseUser.getRoleId().equals("")){
                geBaseUserRoleService.deleteById(geBaseUser.getUserId());
                String[] roles=geBaseUser.getRoleId().split(",");
                for (String role:roles){
                    GeBaseUserRole geBaseUserRole=new GeBaseUserRole();
                    geBaseUserRole.setUserId(geBaseUser.getUserId());
                    geBaseUserRole.setRoleId(Integer.parseInt(role));
                    geBaseUserRoleService.insert(geBaseUserRole);
                }
            }
            result.setCode(200);
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(500);
        }

        return result;
    }

    /**
     * 删除用户
     */
    @PostMapping(value = "/deleteUser")
    @Transactional
    public CommonResult<JSONObject> deleteUser(int userId){
        CommonResult<JSONObject> result=new CommonResult<>();
        try {
            GeBaseUser geBaseUser = geBaseUserService.getUserById(userId);
            geBaseUserService.deleteById(userId);
            geBaseUserRoleService.deleteById(userId);
//            carbonBackTask.deleteUser(geBaseUser.getPhone());
            result.setCode(200);
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(500);
        }

        return result;
    }

    /**
     * 冻结用户
     */
    @GetMapping(value = "/freezeUser")
    public CommonResult<JSONObject> freezeUser(@RequestBody GeBaseUser geBaseUser){
        CommonResult<JSONObject> result=new CommonResult<>();
        try {
            geBaseUserService.update(geBaseUser);
            result.setCode(200);
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(500);
        }
        return result;
    }

    /**
     * 启动用户账号
     */
    @GetMapping(value = "/switchUser")
    public CommonResult<JSONObject> switchUser(@RequestBody GeBaseUser geBaseUser){
        CommonResult<JSONObject> result=new CommonResult<>();
        try {
            geBaseUserService.update(geBaseUser);
            result.setCode(200);
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(500);
        }
        return result;
    }

    /**
     * 检索用户信息
     */
    @GetMapping(value = "/searchUserInfo")
    public CommonResult<List<GeBaseUser>> searchUserInfo(String value,Integer type,Integer status,String starttime,String endtime,String birstime,String biretime,Integer pageNum,Integer pageSize){
        CommonResult<List<GeBaseUser>> result=new CommonResult<>();
        try {
            if (pageSize!=null){
                List<GeBaseUser> list=geBaseUserService.getAllUserByValue(value,type,status,starttime,endtime,birstime,biretime,null,(pageNum-1)*pageSize,pageSize);
                for (GeBaseUser geBaseUser:list){
                    List<GeBaseUserRole> list2=geBaseUserRoleService.getUserRoleByUserId(geBaseUser.getUserId());
                    if (list2!=null&&list2.size()>0){
                        GeBaseRole geBaseRole=geBaseRoleService.queryById(list2.get(0).getRoleId());
                        geBaseUser.setRoleName(geBaseRole.getRoleName());
                    }
                    if(null!=geBaseUser.getDeptId()){
                        //查询部门名称
                        geBaseUser.setDeptName(geBaseDepartService.getById(String.valueOf(geBaseUser.getDeptId())).getDepartName());
                    }
                }
                List<GeBaseUser> list1=geBaseUserService.getAllUserByValue(value,type,status,starttime,endtime,birstime,biretime,null,0,0);
                result.setData(list);
                result.setMessage(String.valueOf(list1.size()));
                result.setCode(200);
            }else {
                List<GeBaseUser> list=geBaseUserService.getAllUserByValue(value,type,status,starttime,endtime,birstime,biretime,null,0,0);
                for (GeBaseUser geBaseUser:list){
                    List<GeBaseUserRole> list2=geBaseUserRoleService.getUserRoleByUserId(geBaseUser.getUserId());
                    if (list2!=null&&list2.size()>0){
                        GeBaseRole geBaseRole=geBaseRoleService.queryById(list2.get(0).getRoleId());
                        geBaseUser.setRoleName(geBaseRole.getRoleName());
                    }
                    if(null!=geBaseUser.getDeptId()){
                        //查询部门名称
                        geBaseUser.setDeptName(geBaseDepartService.getById(String.valueOf(geBaseUser.getDeptId())).getDepartName());
                    }
                }
                List<GeBaseUser> list1=geBaseUserService.getAllUserByValue(value,type,status,starttime,endtime,birstime,biretime,null,0,0);
                result.setData(list);
                result.setMessage(String.valueOf(list1.size()));
                result.setCode(200);
            }
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(500);
        }
        return result;
    }

    /**
     * 用户导出
     */
    @GetMapping(value = "/exportUserInfo")
    public void exportUserInfo(HttpServletRequest request, HttpServletResponse res,String value,Integer type,Integer status,String starttime,String endtime,String birstime,String biretime,String ids){
        List<GeBaseUser> list=null;
        if (ids!=null&&!ids.equals("")){
            list=geBaseUserService.getAllUserByValue(value,type,status,starttime,endtime,birstime,biretime,ids.split(","),0,0);
//            list=geBaseUserService.getAllUserByValueAndIds(value,ids.split(","));
        }else {
            list=geBaseUserService.getAllUserByValue(value,type,status,starttime,endtime,birstime,biretime,null,0,0);
        }
        File file=createUserExcelFile(list);
        FileUtils.downloadFile(request,res, file, "用户信息.xlsx");
    }

    public  File createUserExcelFile(List<?> records) {
        if (records == null) {
            records = new ArrayList<>();
        }
        Workbook workbook = new XSSFWorkbook();
        //创建一个sheet，括号里可以输入sheet名称，默认为sheet0
        Sheet sheet = workbook.createSheet();
        Row row0 = sheet.createRow(0);
        int columnIndex = 0;
        row0.createCell(columnIndex).setCellValue("序号");
        row0.createCell(++columnIndex).setCellValue("姓名");
        row0.createCell(++columnIndex).setCellValue("角色");
        row0.createCell(++columnIndex).setCellValue("出生年月");
        row0.createCell(++columnIndex).setCellValue("手机号");
//        row0.createCell(++columnIndex).setCellValue("姓名");
        row0.createCell(++columnIndex).setCellValue("性别");
        row0.createCell(++columnIndex).setCellValue("创建时间");
        row0.createCell(++columnIndex).setCellValue("账户状态");

        for (int i = 0; i < records.size(); i++) {
            GeBaseUser user = (GeBaseUser) records.get(i);
            Row row = sheet.createRow(i + 1);
            for (int j = 0; j < columnIndex + 1; j++) {
                row.createCell(j);
            }
            columnIndex = 0;
            row.getCell(columnIndex).setCellValue(i + 1);
            row.getCell(++columnIndex).setCellValue(user.getUsername());
            if (user.getRoleId()!=null){
                GeBaseRole geBaseRole=geBaseRoleService.queryById(Integer.parseInt(user.getRoleId()));
                row.getCell(++columnIndex).setCellValue(geBaseRole==null?"":geBaseRole.getRoleName());
            }else {
                row.getCell(++columnIndex).setCellValue("");
            }
            row.getCell(++columnIndex).setCellValue(user.getBirthday());
            row.getCell(++columnIndex).setCellValue(user.getPhone());
//            row.getCell(++columnIndex).setCellValue(user.getNickname());
            row.getCell(++columnIndex).setCellValue(user.getSex()==null?null:(user.getSex()==0?"男":(user.getSex()==1?"女":"未设置")));
            row.getCell(++columnIndex).setCellValue(sf.format(user.getCreateTime()));
            row.getCell(++columnIndex).setCellValue(user.getDelFlag()==0?"正常":(user.getDelFlag()==1?"删除":"停用"));
        }
        //调用PoiUtils工具包
        return PoiUtils.createExcelFile(workbook, "user_info");
    }

    /**
     *  用户详情
     */
    @GetMapping(value = "/userDetail")
    public CommonResult<GeBaseUser> userDetail(int userId){
        CommonResult<GeBaseUser> result = new CommonResult<>();
        try {
            GeBaseUser geBaseUser=geBaseUserService.queryById(userId);
/*            List<GeBaseUserRole> list=geBaseUserRoleService.getUserRoleByUserId(geBaseUser.getUserId());
            if (list!=null&&list.size()>0){
                GeBaseRole geBaseRole=geBaseRoleService.queryById(list.get(0).getRoleId());
            }*/
//            List<GeBaseUserRole> list=geBaseUserRoleService.getUserRoleByUserId(userId);
            result.setCode(200);
            result.setData(geBaseUser);
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(500);
        }
        return result;
    }

    /**
     *  用户详情
     */
    @GetMapping(value = "/userDetailWx")
    public CommonResult<GeBaseUser> userDetailWx(int userId){
        CommonResult<GeBaseUser> result = new CommonResult<>();
        try {
            GeBaseUser geBaseUser=geBaseUserService.queryById(userId);
//            List<GeBaseUserRole> list=geBaseUserRoleService.getUserRoleByUserId(userId);
            result.setCode(200);
            result.setData(geBaseUser);
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(500);
        }
        return result;
    }

    /**
     * 修改密码
     */
    @PostMapping(value = "/updatepwd")
    public CommonResult<JSONObject> updatepwd(@RequestBody GeBaseUser geBaseUser) throws InvalidKeySpecException, NoSuchAlgorithmException {
        CommonResult<JSONObject> result = new CommonResult<>();
        try {
            String pwd=geBaseUser.getPassword();
            geBaseUser.setPassword(RSAUtils.publicEncrypt(pwd,RSAUtils.getPublicKey(pubKey)));
            geBaseUserService.update(geBaseUser);
            result.setCode(200);
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(500);
        }
        return result;
    }

    public String addRetailinfo(GeBaseUser geBaseUser){
        net.sf.json.JSONObject bodyParams = new net.sf.json.JSONObject();
        // 公共参数
        bodyParams.put("appKey", "chinaumsandroidpos");
        bodyParams.put("methodVer", "1.0");
        bodyParams.put("nonceStr", "D1K2");

        //业务参数
        bodyParams.put("branId", branId);
        bodyParams.put("mobileNo", geBaseUser.getPhone());
        bodyParams.put("vipName", geBaseUser.getUsername());


        String signKey = "xyz123";
        List<org.apache.http.Header> headerList=new ArrayList<Header>();
        BasicHeader header=new BasicHeader("signKey", signKey);
        headerList.add(header);

        bodyParams.put("sign", SHAUtils.getSign(bodyParams, signKey, "UTF-8"));
//        System.out.println(bodyParams.toString());
        //String result = testPost(url, bodyParams.toString(), signKey);

        StringEntity jsonEntity = new StringEntity(bodyParams.toString(), ContentType.APPLICATION_JSON);
        String result=SHAUtils.testPost(regUrl,jsonEntity,(org.apache.http.Header[])headerList.toArray(new BasicHeader[0]));
        JSONObject jsonObject=JSON.parseObject(result);
        if (jsonObject.getString("vipCard")!=null){
            if (jsonObject.getJSONObject("vipCard").getString("typeId")!=null){
                GeBaseUserRetail geBaseUserRetail = new GeBaseUserRetail();
                geBaseUserRetail.setUserId(geBaseUser.getUserId());
                geBaseUserRetail.setTypeid(jsonObject.getJSONObject("vipCard").getInteger("typeId"));
                geBaseUserRetailService.insert(geBaseUserRetail);
            }
        }else {
            return "error";
        }
        return result;
    }

/*
    *//**
     * 查询会员信息
     *//*
    @GetMapping(value = "/vipQueryApi")
    public String vipQueryApi(String mobileNo){
        net.sf.json.JSONObject bodyParams = new net.sf.json.JSONObject();
        // 公共参数
        bodyParams.put("appKey", "chinaumsandroidpos");
        bodyParams.put("methodVer", "1.0");
        bodyParams.put("nonceStr", "D1K2");

        //业务参数
        bodyParams.put("mobileNo", mobileNo);


        String signKey = "xyz123";
        List<org.apache.http.Header> headerList=new ArrayList<Header>();
        BasicHeader header=new BasicHeader("signKey", signKey);
        headerList.add(header);

        bodyParams.put("sign", SHAUtils.getSign(bodyParams, signKey, "UTF-8"));
        System.out.println(bodyParams.toString());
        //String result = testPost(url, bodyParams.toString(), signKey);

        StringEntity jsonEntity = new StringEntity(bodyParams.toString(), ContentType.APPLICATION_JSON);
        String result=SHAUtils.testPost(queryUrl,jsonEntity,(org.apache.http.Header[])headerList.toArray(new BasicHeader[0]));
        System.out.println(result);
        return result;
    }

    public String deleteRetailinfo(GeBaseUser geBaseUser){
        net.sf.json.JSONObject bodyParams = new net.sf.json.JSONObject();
        // 公共参数
        bodyParams.put("appKey", "chinaumsandroidpos");
        bodyParams.put("methodVer", "1.0");
        bodyParams.put("nonceStr", "D1K2");

        //业务参数
        bodyParams.put("mobileNo", geBaseUser.getPhone());


        String signKey = "xyz123";
        List<org.apache.http.Header> headerList=new ArrayList<Header>();
        BasicHeader header=new BasicHeader("signKey", signKey);
        headerList.add(header);

        bodyParams.put("sign", SHAUtils.getSign(bodyParams, signKey, "UTF-8"));
        System.out.println(bodyParams.toString());
        //String result = testPost(url, bodyParams.toString(), signKey);

        StringEntity jsonEntity = new StringEntity(bodyParams.toString(), ContentType.APPLICATION_JSON);
        String result=SHAUtils.testPost(deleteUrl,jsonEntity,(org.apache.http.Header[])headerList.toArray(new BasicHeader[0]));
        System.out.println(result);
        return result;
    }

    *//**
     * 获取指定用户/会员的消费订单列表接口
     * @return
     *//*
    @GetMapping(value = "/vipTransQuery")
    public CommonResult<JSONObject> vipTransQuery(String mobileNo,String timeBegin,String timeEnd,String pageNo,String pageSize){
        CommonResult<JSONObject> result = new CommonResult<>();
        try {
            net.sf.json.JSONObject bodyParams = new net.sf.json.JSONObject();
            // 公共参数
            bodyParams.put("appKey", "chinaumsandroidpos");
            bodyParams.put("methodVer", "1.0");
            bodyParams.put("nonceStr", "D1K2");

            //业务参数
            bodyParams.put("mobileNo", mobileNo);
            bodyParams.put("timeBegin", timeBegin);
            bodyParams.put("timeEnd", timeEnd);
            bodyParams.put("pageNo", pageNo);
            bodyParams.put("pageSize", pageSize);


            String signKey = "xyz123";
            List<org.apache.http.Header> headerList=new ArrayList<Header>();
            BasicHeader header=new BasicHeader("signKey", signKey);
            headerList.add(header);

            bodyParams.put("sign", SHAUtils.getSign(bodyParams, signKey, "UTF-8"));
            System.out.println(bodyParams.toString());
            //String result = testPost(url, bodyParams.toString(), signKey);

            StringEntity jsonEntity = new StringEntity(bodyParams.toString(), ContentType.APPLICATION_JSON);
            String res=SHAUtils.testPost(transQuery,jsonEntity,(org.apache.http.Header[])headerList.toArray(new BasicHeader[0]));
            result.setCode(200);
            result.setData(JSON.parseObject(res));
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(500);
        }
        return result;
    }

    *//**
     * 获取指定订单号的消费订单详情接口
     *//*
    @GetMapping("/getTranInfo")
    public String getTranInfo(String tranId){
        net.sf.json.JSONObject bodyParams = new net.sf.json.JSONObject();
        // 公共参数
        bodyParams.put("appKey", "chinaumsandroidpos");
        bodyParams.put("methodVer", "1.0");
        bodyParams.put("nonceStr", "D1K2");

        //业务参数
        bodyParams.put("tranId", tranId);


        String signKey = "xyz123";
        List<org.apache.http.Header> headerList=new ArrayList<Header>();
        BasicHeader header=new BasicHeader("signKey", signKey);
        headerList.add(header);

        bodyParams.put("sign", SHAUtils.getSign(bodyParams, signKey, "UTF-8"));
        System.out.println(bodyParams.toString());
        //String result = testPost(url, bodyParams.toString(), signKey);

        StringEntity jsonEntity = new StringEntity(bodyParams.toString(), ContentType.APPLICATION_JSON);
        String result=SHAUtils.testPost(tranInfo,jsonEntity,(org.apache.http.Header[])headerList.toArray(new BasicHeader[0]));
        System.out.println(result);
        return result;
    }

    *//**
     * 礼金券规则列表获取接口
     *//*
    @GetMapping("/exGiftRule")
    public String exGiftRule(int userId){
        GeBaseUserRetail geBaseUserRetail=geBaseUserRetailService.queryById(userId);
        net.sf.json.JSONObject bodyParams = new net.sf.json.JSONObject();
        // 公共参数
        bodyParams.put("appKey", "chinaumsandroidpos");
        bodyParams.put("methodVer", "1.0");
        bodyParams.put("nonceStr", "D1K2");

        //业务参数
        bodyParams.put("branId", branId);
        bodyParams.put("typeId", geBaseUserRetail.getTypeid());


        String signKey = "xyz123";
        List<org.apache.http.Header> headerList=new ArrayList<Header>();
        BasicHeader header=new BasicHeader("signKey", signKey);
        headerList.add(header);

        bodyParams.put("sign", SHAUtils.getSign(bodyParams, signKey, "UTF-8"));
        System.out.println(bodyParams.toString());
        //String result = testPost(url, bodyParams.toString(), signKey);

        StringEntity jsonEntity = new StringEntity(bodyParams.toString(), ContentType.APPLICATION_JSON);
        String result=SHAUtils.testPost(giftRule,jsonEntity,(org.apache.http.Header[])headerList.toArray(new BasicHeader[0]));
        System.out.println(result);
        return result;
    }

    *//**
     * 礼金券兑换接口
     *//*
    @GetMapping("/giftExchangeApi")
    public String giftExchangeApi(String rdid,String pluId,String mobileNo,int qty){
        net.sf.json.JSONObject bodyParams = new net.sf.json.JSONObject();
        // 公共参数
        bodyParams.put("appKey", "chinaumsandroidpos");
        bodyParams.put("methodVer", "1.0");
        bodyParams.put("nonceStr", "D1K2");

        //业务参数
        bodyParams.put("mobileNo", mobileNo);
        bodyParams.put("pluId", pluId);
        bodyParams.put("qty", qty);
        bodyParams.put("rdid", rdid);



        String signKey = "xyz123";
        List<org.apache.http.Header> headerList=new ArrayList<Header>();
        BasicHeader header=new BasicHeader("signKey", signKey);
        headerList.add(header);

        bodyParams.put("sign", SHAUtils.getSign(bodyParams, signKey, "UTF-8"));
        System.out.println(bodyParams.toString());
        //String result = testPost(url, bodyParams.toString(), signKey);

        StringEntity jsonEntity = new StringEntity(bodyParams.toString(), ContentType.APPLICATION_JSON);
        String result=SHAUtils.testPost(giftExchange,jsonEntity,(org.apache.http.Header[])headerList.toArray(new BasicHeader[0]));
        System.out.println(result);
        return result;
    }
    *//**
     * 个人礼金券获取接口
     *//*
    @GetMapping("/vipCouponQueryApi")
    public String vipCouponQueryApi(String mobileNo){
        net.sf.json.JSONObject bodyParams = new net.sf.json.JSONObject();
        // 公共参数
        bodyParams.put("appKey", "chinaumsandroidpos");
        bodyParams.put("methodVer", "1.0");
        bodyParams.put("nonceStr", "D1K2");

        //业务参数
        bodyParams.put("mobileNo", mobileNo);




        String signKey = "xyz123";
        List<org.apache.http.Header> headerList=new ArrayList<Header>();
        BasicHeader header=new BasicHeader("signKey", signKey);
        headerList.add(header);

        bodyParams.put("sign", SHAUtils.getSign(bodyParams, signKey, "UTF-8"));
        System.out.println(bodyParams.toString());
        //String result = testPost(url, bodyParams.toString(), signKey);

        StringEntity jsonEntity = new StringEntity(bodyParams.toString(), ContentType.APPLICATION_JSON);
        String result=SHAUtils.testPost(vipCoupon,jsonEntity,(org.apache.http.Header[])headerList.toArray(new BasicHeader[0]));
        System.out.println(result);
        return result;
    }*/


    //-------------------------- 角色管理 --------------------------------



    /**
     * 添加用户角色
     */
    @PostMapping(value = "/addRole")
    public CommonResult<GeBaseRole> addRole(@RequestBody GeBaseRole geBaseRole){
        CommonResult<GeBaseRole> result=new CommonResult<>();
        try {
            List<GeBaseRole> list=geBaseRoleService.queryByRoleName(geBaseRole.getRoleName());
            if (list!=null&&list.size()>0){
                result.setCode(300);
                result.setMessage("角色名称重复!");
                return result;
            }
            List<GeBaseRole> glist=geBaseRoleService.queryByRoleCode(geBaseRole.getRoleCode());
            if (glist!=null&&glist.size()>0){
                result.setCode(300);
                result.setMessage("角色编码重复!");
                return result;
            }
            geBaseRoleService.insert(geBaseRole);
            result.setData(geBaseRole);
            result.setCode(200);
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(500);
        }
        return result;
    }

    /**
     * 编辑用户角色
     */
    @PostMapping(value = "/editRole")
    public CommonResult<JSONObject> editRole(@RequestBody GeBaseRole geBaseRole){
        CommonResult<JSONObject> result=new CommonResult<>();
        try {
            GeBaseRole gb=geBaseRoleService.queryById(geBaseRole.getRoleId());
            if (!gb.getRoleName().equals(geBaseRole.getRoleName())){
                List<GeBaseRole> list=geBaseRoleService.queryByRoleName(geBaseRole.getRoleName());
                if (list!=null&&list.size()>0){
                    result.setCode(300);
                    result.setMessage("角色名称重复!");
                    return result;
                }
            }
            if (!gb.getRoleCode().equals(geBaseRole.getRoleCode())){
                List<GeBaseRole> glist=geBaseRoleService.queryByRoleCode(geBaseRole.getRoleCode());
                if (glist!=null&&glist.size()>0){
                    result.setCode(300);
                    result.setMessage("角色编码重复!");
                    return result;
                }
            }
            geBaseRoleService.update(geBaseRole);
            result.setCode(200);
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(500);
        }
        return result;
    }

    /**
     * 删除用户角色
     */
    @PostMapping(value = "/deleteRole")
    public CommonResult<JSONObject> deleteRole(@RequestBody GeBaseRole geBaseRole){
        CommonResult<JSONObject> result=new CommonResult<>();
        try {
            List<GeBaseUserRole> list=geBaseUserRoleService.getUserRoleByRoleId(geBaseRole.getRoleId());
            if (list!=null&&list.size()>0){
                result.setCode(300);
                result.setMessage("该角色已有用户绑定，请先解除绑定!");
                return result;
            }
            geBaseRoleService.deleteById(geBaseRole.getRoleId());
            geBaseRoleMenuService.deleteById(geBaseRole.getRoleId());
            result.setCode(200);
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(500);
        }
        return result;
    }

    /**
     * 查询用户角色列表
     */
    @GetMapping(value = "/searchRoleList")
    public CommonResult<List<GeBaseRole>> searchRoleList(String value,int pageNum,int pageSize){
        CommonResult<List<GeBaseRole>> result=new CommonResult<>();
        try {
            List<GeBaseRole> list=geBaseRoleService.getRolesByValue(value,(pageNum-1)*pageSize,pageSize);
            List<GeBaseRole> list1=geBaseRoleService.getRolesByValue(value,0,0);
            result.setData(list);
            result.setMessage(String.valueOf(list1.size()));
            result.setCode(200);
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(500);
        }
        return result;
    }

    /**
     * 配置角色权限
     */
    @PostMapping(value = "/configureRolePermissions")
    public CommonResult<JSONObject> configureRolePermissions(Integer role_id,String menus){
        CommonResult<JSONObject> result=new CommonResult<>();
        try {
            geBaseRoleMenuService.deleteById(role_id);
            String[] menu=menus.split(",");
            for (String m:menu){
                int menu_id=Integer.parseInt(m);
                GeBaseRoleMenu geBaseRoleMenu = new GeBaseRoleMenu();
                geBaseRoleMenu.setRoleId(role_id);
                geBaseRoleMenu.setMenuId(menu_id);
                geBaseRoleMenuService.insert(geBaseRoleMenu);
            }
            result.setCode(200);
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(500);
        }
        return result;
    }

    /**
     * 获取角色权限树
     */
    @GetMapping(value = "/getRolePermissions")
    public  CommonResult<List<GeBaseMenu>> getRolePermissions(int role_id){
        CommonResult<List<GeBaseMenu>> result = new CommonResult<>();
        try {
            List<GeBaseRoleMenu> grlist=geBaseRoleMenuService.queryById(role_id);
            String menus="";
            for (GeBaseRoleMenu g:grlist){
                menus+=g.getMenuId()+",";
            }
            List<GeBaseMenu>  glist=geBaseMenuService.getMenuByParentId(0);
            if (glist.size()>0){
                for (GeBaseMenu geBaseMenu:glist){
                    if (ArrayUtils.contains(menus.split(","),geBaseMenu.getMenuId().toString())){
                        geBaseMenu.setCheck(true);
                    }else {
                        geBaseMenu.setCheck(false);
                    }
                    geBaseMenu.setChildren(menusNodeMerge(geBaseMenu,menus));
                }
            }
            result.setCode(200);
            result.setData(glist);
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(500);
        }
        return  result;
    }

    public List<GeBaseMenu> menusNodeMerge( GeBaseMenu geBaseMenu,String menus){
        List<GeBaseMenu> gblist=geBaseMenuService.getMenuByParentId(geBaseMenu.getMenuId());
        for (GeBaseMenu gb:gblist){
            if (ArrayUtils.contains(menus.split(","),gb.getMenuId().toString())){
                gb.setCheck(true);
            }else {
                gb.setCheck(false);
            }
            gb.setChildren(menusNodeMerge(gb,menus));
        }
        return gblist;
    }

    /**
     * 角色导出
     */
    @GetMapping(value = "/exportRole")
    public void exportRole(HttpServletRequest request,HttpServletResponse response,String value,String ids){
        List<GeBaseRole> list=null;
        if (ids!=null&&!ids.equals("")){
            list=geBaseRoleService.getRolesByValueAndIds(value,ids.split(","));
        }else {
            list=geBaseRoleService.getRolesByValue(value,0,0);
        }
        File file=createRoleExcelFile(list);
        FileUtils.downloadFile(request,response, file, "角色信息.xlsx");
    }


    public static File createRoleExcelFile(List<?> records) {
        if (records == null) {
            records = new ArrayList<>();
        }
        Workbook workbook = new XSSFWorkbook();
        //创建一个sheet，括号里可以输入sheet名称，默认为sheet0
        Sheet sheet = workbook.createSheet();
        Row row0 = sheet.createRow(0);
        int columnIndex = 0;
        row0.createCell(columnIndex).setCellValue("序号");
        row0.createCell(++columnIndex).setCellValue("角色名称");
        row0.createCell(++columnIndex).setCellValue("角色编码");
        row0.createCell(++columnIndex).setCellValue("角色描述");
        row0.createCell(++columnIndex).setCellValue("创建时间");

        for (int i = 0; i < records.size(); i++) {
            GeBaseRole role = (GeBaseRole) records.get(i);
            Row row = sheet.createRow(i + 1);
            for (int j = 0; j < columnIndex + 1; j++) {
                row.createCell(j);
            }
            columnIndex = 0;
            row.getCell(columnIndex).setCellValue(i + 1);
            row.getCell(++columnIndex).setCellValue(role.getRoleName());
            row.getCell(++columnIndex).setCellValue(role.getRoleCode());
            row.getCell(++columnIndex).setCellValue(role.getRoleDesc());
            row.getCell(++columnIndex).setCellValue(sf.format(role.getCreateTime()));
        }
        //调用PoiUtils工具包
        return PoiUtils.createExcelFile(workbook, "role_info");
    }


    //-------------------------- 权限管理 --------------------------------


    /**
     * 新增权限功能节点
     */
    @PostMapping(value = "/addAuthority")
    public CommonResult<JSONObject> addAuthority(@RequestBody GeBaseMenu geBaseMenu){
        CommonResult<JSONObject> result=new CommonResult<>();
        try {
            geBaseMenuService.insert(geBaseMenu);
            result.setCode(200);
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(500);
        }
        return result;
    }

    /**
     * 编辑权限功能节点
     */
    @PostMapping(value = "/editAuthority")
    public CommonResult<JSONObject> editAuthority(@RequestBody GeBaseMenu geBaseMenu){
        CommonResult<JSONObject> result=new CommonResult<>();
        try {
            geBaseMenuService.update(geBaseMenu);
            result.setCode(200);
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(500);
        }
        return result;
    }

    /**
     * 删除权限功能节点
     */
    @PostMapping(value = "/deleteAuthority")
    public CommonResult<JSONObject> deleteAuthority(@RequestBody GeBaseMenu geBaseMenu){
        CommonResult<JSONObject> result=new CommonResult<>();
        try {
            geBaseMenuService.deleteById(geBaseMenu.getMenuId());
            result.setCode(200);
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(500);
        }
        return result;
    }

    /**
     * 获取权限功能树
     */
    @GetMapping(value = "/searchAuthorityTree")
    public CommonResult<List<GeBaseMenu>> searchAuthorityTree(){
        CommonResult<List<GeBaseMenu>> result=new CommonResult<>();
        try {
            List<GeBaseMenu> glist=geBaseMenuService.getMenuByParentId(0);
            if (glist.size()>0){
                for (GeBaseMenu geBaseMenu:glist){
                    geBaseMenu.setChildren(menuxNode(geBaseMenu));
                }
            }
            result.setCode(200);
            result.setData(glist);
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(500);
        }
        return result;
    }

    public List<GeBaseMenu> menuxNode(@RequestBody GeBaseMenu geBaseMenu){
        List<GeBaseMenu> gblist=geBaseMenuService.getMenuByParentId(geBaseMenu.getMenuId());
        for (GeBaseMenu gb:gblist){
            gb.setChildren(menuxNode(gb));
        }
        return gblist;
    }

    /**
     * 获取所有菜单
     */
    @GetMapping("/searchAllAuthority")
    public CommonResult<List<GeBaseMenu>> searchAllAuthority(HttpServletRequest request){
        CommonResult<List<GeBaseMenu>> result = new CommonResult<>();
        try {
            String access_token=request.getHeader("access_token");
            GeOuthToken geOuthToken=geOuthTokenService.queryById(access_token);
            Integer userId=geOuthToken.getUserId();
            List<GeBaseUserRole> list=geBaseUserRoleService.getUserRoleByUserId(userId);
            List<GeBaseMenu> glist=geBaseMenuService.getAllMenu(list.get(0).getRoleId());
            result.setCode(200);
            result.setData(glist);
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(500);
        }
        return result;
    }



    //-------------------------- 快捷入口管理 --------------------------------

    /**
     *添加快捷入口
     */
    @PostMapping(value = "/addQuickEntry")
    @ApiOperation("添加快捷入口")
    public CommonResult<JSONObject> addQuickEntry(@RequestBody GeBaseEntry geBaseEntry){
        CommonResult<JSONObject> result = new CommonResult<>();
        try {
            geBaseEntryService.insert(geBaseEntry);
            result.setCode(200);
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(500);
        }
        return result;
    }

    /**
     * 编辑快捷入口
     */
    @PostMapping(value = "/editQuickEntry")
    @ApiOperation("编辑快捷入口")
    public CommonResult<JSONObject> editQuickEntry(@RequestBody GeBaseEntry geBaseEntry){
        CommonResult<JSONObject> result = new CommonResult<>();
        try {
            geBaseEntryService.update(geBaseEntry);
            result.setCode(200);
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(500);
        }
        return result;
    }

    /**
     * 删除快捷入口
     */
    @PostMapping(value = "/deleteQuickEntry")
    public CommonResult<JSONObject> deleteQuickEntry(int entryId){
        CommonResult<JSONObject> result = new CommonResult<>();
        try {
            geBaseEntryService.deleteById(entryId);
            result.setCode(200);
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(500);
        }
        return result;
    }

    /**
     * 快捷入口顺序编辑
     */
    @PostMapping(value = "/editQuickEntryOrder")
    public CommonResult<JSONObject> editQuickEntryOrder(String entryIds,String sorts){
        CommonResult<JSONObject> result = new CommonResult<>();
        try {
            String[] eIds=entryIds.split(",");
            String[] sIds=sorts.split(",");
            for (int i=0;i<eIds.length;i++){
                GeBaseEntry geBaseEntry=new GeBaseEntry();
                geBaseEntry.setEntryId(Integer.parseInt(eIds[i]));
                geBaseEntry.setSort(Integer.parseInt(sIds[i]));
                geBaseEntryService.update(geBaseEntry);
            }
            result.setCode(200);
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(500);
        }
        return result;
    }

    /**
     * 获取快捷入口列表
     */
    @PostMapping(value = "/searchQuickEntry")
    @ApiOperation("获取快捷入口列表")
    @SecurityParameter
    public CommonResult<List<GeBaseEntry>> searchQuickEntry(@RequestBody String s){
        CommonResult<List<GeBaseEntry>> result = new CommonResult<>();
        try {
            JSONObject jsonObject= JSON.parseObject(s);
            String value=jsonObject.getString("value");
            Integer type=jsonObject.getInteger("type");
            Integer delFlag=jsonObject.getInteger("delFlag");
            Integer pageNum=jsonObject.getInteger("pageNum");
            Integer pageSize=jsonObject.getInteger("pageSize");
            List<GeBaseEntry> list=geBaseEntryService.getEntriesByValue(value,(pageNum-1)*pageSize,pageSize,delFlag,type);
            List<GeBaseEntry> list1=geBaseEntryService.getEntriesByValue(value,(pageNum-1)*pageSize,0,delFlag, type);
            result.setData(list);
            result.setCode(200);
            result.setMessage(String.valueOf(list1.size()));
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(500);
        }
        return result;
    }

//    /**
//     * 获取快捷入口列表
//     */
//    @PostMapping(value = "/searchQuickEntryWx")
//    @SecurityParameter
//    public CommonResult<List<GeBaseEntry>> searchQuickEntryWx(@RequestBody String s){
//        CommonResult<List<GeBaseEntry>> result = new CommonResult<>();
//        try {
//            JSONObject jsonObject=JSON.parseObject(s);
//            String value=jsonObject.getString("value");
//            Integer delFlag=jsonObject.getInteger("delFlag");
//            Integer pageNum=jsonObject.getInteger("pageNum");
//            Integer pageSize=jsonObject.getInteger("pageSize");
//            List<GeBaseEntry> list=geBaseEntryService.getEntriesByValue(value,(pageNum-1)*pageSize,pageSize, delFlag);
//            List<GeBaseEntry> list1=geBaseEntryService.getEntriesByValue(value,(pageNum-1)*pageSize,0, delFlag);
//            result.setData(list);
//            result.setCode(200);
//            result.setMessage(String.valueOf(list1.size()));
//        }catch (Exception e){
//            e.printStackTrace();
//            result.setCode(500);
//        }
//        return result;
//    }

    /**
     * 快捷入口图标
     */

    @GetMapping("/quickEntryicon")
    public CommonResult<JSONObject> quickEntryicon(){
        CommonResult<JSONObject> result = new CommonResult<>();
        return result;
    }
    /**
     * 快捷入口链接
     */

    @GetMapping("/quickEntrylink")
    public CommonResult<JSONObject> quickEntrylink(){
        CommonResult<JSONObject> result = new CommonResult<>();
        return result;
    }


    //-------------------------- 组织结构管理 --------------------------------


    /**
     * 添加组织结构节点
     */
    @PostMapping(value = "/addOrganization")
    public CommonResult<JSONObject> addOrganization(@RequestBody GeBaseOrg geBaseOrg){
        CommonResult<JSONObject> result = new CommonResult<>();
        try {
            geBaseOrgService.insert(geBaseOrg);
            result.setCode(200);
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(500);
        }
        return result;
    }

    /**
     * 编辑组织结构节点
     */
    @PostMapping(value = "/editOrganization")
    public CommonResult<JSONObject> editOrganization(@RequestBody GeBaseOrg geBaseOrg){
        CommonResult<JSONObject> result = new CommonResult<>();
        try {
            geBaseOrgService.update(geBaseOrg);
            result.setCode(200);
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(500);
        }
        return result;
    }

    /**
     * 删除组织结构节点
     */
    @PostMapping(value = "/deleteOrganization")
    public CommonResult<JSONObject> deleteOrganization(int orgId){
        CommonResult<JSONObject> result = new CommonResult<>();
        try {
            geBaseOrgService.deleteById(orgId);
            result.setCode(200);
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(500);
        }
        return result;
    }

    /**
     * 获取组织结构树形列表
     */
    @GetMapping(value = "/searchOrganization")
    public CommonResult<List<GeBaseOrg>> searchOrganization(){
        CommonResult<List<GeBaseOrg>> result = new CommonResult<>();
        try {
            List<GeBaseOrg> glist=geBaseOrgService.getOrganizationByParentId(0);
            if (glist.size()>0){
                for (GeBaseOrg geBaseOrg:glist){
                    geBaseOrg.setChildren(organizationNode(geBaseOrg));
                }
            }
            result.setData(glist);
            result.setCode(200);
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(500);
        }
        return result;
    }

    public List<GeBaseOrg> organizationNode(@RequestBody GeBaseOrg geBaseOrg){
        List<GeBaseOrg> golist=geBaseOrgService.getOrganizationByParentId(geBaseOrg.getOrgId());
        for (GeBaseOrg go:golist){
            go.setChildren(organizationNode(go));
        }
        return golist;
    }

    /**
     * 查看组织机构详情
     */
    @GetMapping(value = "/searchOrganizationInfo")
    public CommonResult<GeBaseOrg> searchOrganizationInfo(int orgId){
        CommonResult<GeBaseOrg> result = new CommonResult<>();
        try {
            GeBaseOrg geBaseOrg=geBaseOrgService.queryById(orgId);
            result.setData(geBaseOrg);
            result.setCode(200);
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(500);
        }
        return  result;
    }

    //-------------------------- 字典管理 --------------------------------

    /**
     * 字典添加
     */
    @PostMapping(value = "/addDictionary")
    public CommonResult<JSONObject> addDictionary(@RequestBody GeBaseDictionary geBaseDictionary){
        CommonResult<JSONObject> result = new CommonResult<>();
        try{
            geBaseDicyionaryService.insert(geBaseDictionary);
            result.setCode(200);
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(500);
        }
        return result;
    }

    /**
     * 字典修改
     */
    @PostMapping(value = "/editDictionary")
    public CommonResult<JSONObject> editDictionary(@RequestBody GeBaseDictionary geBaseDictionary){
        CommonResult<JSONObject> result = new CommonResult<>();
        try{
            geBaseDicyionaryService.update(geBaseDictionary);
            result.setCode(200);
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(500);
        }
        return result;
    }

    /**
     * 字典删除
     */
    @PostMapping(value = "/deleteDictionary")
    public CommonResult<JSONObject> deleteDictionary(int dictionaryId){
        CommonResult<JSONObject> result = new CommonResult<>();
        try{
            geBaseDicyionaryService.deleteById(dictionaryId);
            result.setCode(200);
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(500);
        }
        return result;
    }

    /**
     * 字典列表查询
     */
    @GetMapping(value = "/searchDictionaryList")
    public CommonResult<List<GeBaseDictionary>> searchDictionaryList(String value,int pageNum,int pageSize){
        CommonResult<List<GeBaseDictionary>> result = new CommonResult<>();
        try {
            List<GeBaseDictionary> list=geBaseDicyionaryService.getDictionariesByValues(value,(pageNum-1)*pageSize,pageSize);
            result.setData(list);
            result.setCode(200);
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(500);
        }
        return result;
    }

    /**
     * 获取天气信息
     */
    @GetMapping(value = "/getWeatherInfo")
    public CommonResult<String> getWeatherInfo(){
        CommonResult<String> result = new CommonResult<>();
        try {
            /*JSONObject info=WeatherUtils.getTodayWeather(weather_url+weather_city+".html");
            System.out.println(info);*/
            /*String params="id="+weather_city;
            String sr=HttpRequest.sendGet(weather_url,params);*/
            /*String params = "city=" + weather_city + "&key=" + weather_key;
            String sr = HttpRequest.sendGet(weather_url, params);*/
            GeWeather geWeather=geWeatherService.queryById(1);
            result.setCode(200);
            result.setData(geWeather.getWeather());
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(500);
        }
        return result;
    }

    /**
     * 获取天气信息
     */
    @GetMapping(value = "/getWeatherInfoWx")
    public CommonResult<String> getWeatherInfoWx(){
        CommonResult<String> result = new CommonResult<>();
        try {
            /*JSONObject info=WeatherUtils.getTodayWeather(weather_url+weather_city+".html");
            System.out.println(info);*/
            /*String params="id="+weather_city;
            String sr=HttpRequest.sendGet(weather_url,params);*/
            /*String params = "city=" + weather_city + "&key=" + weather_key;
            String sr = HttpRequest.sendGet(weather_url, params);*/
            GeWeather geWeather=geWeatherService.queryById(1);
            result.setCode(200);
            result.setData(geWeather.getWeather());
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(500);
        }
        return result;
    }
//    @Scheduled(cron = "0 0/30 * * * ?")
    @GetMapping("/getWeather")
    public void getWeather(){
        String params="id="+weather_city;
        String sr=HttpRequest.sendGet(weather_url,params);
        GeWeather geWeather=geWeatherService.queryById(1);
        if (geWeather==null){
            GeWeather geWeather1 = new GeWeather();
            geWeather1.setWeather(sr);
            geWeatherService.insert(geWeather1);
        }else {
            geWeather.setWeather(sr);
            geWeatherService.update(geWeather);
        }
    }
    @GetMapping("/getWeatherNew")
    @ApiOperation("获取天气")
    public JSONObject getWeatherNew(){
        JSONObject weatherData = null;

        try {

            weatherData = geConWeatherService.getWeather();
            //判断当前天气情况
            String weather = weatherData.getString("weather");

            switch (weather){
                case "多云":
                    weatherData.put("url",local_url+"weather/阴.png");
                    weatherData.put("logo","icon-duoyun");
                    break;
                case "阴":
                    weatherData.put("url",local_url+"weather/阴.png");
                    weatherData.put("logo","icon-yintian");
                    break;
                case "雾":
                    weatherData.put("url",local_url+"weather/阴.png");
                    weatherData.put("logo","icon-wu");
                    break;
                case "霾":
                    weatherData.put("url",local_url+"weather/阴.png");
                    weatherData.put("logo","icon-wumai");
                    break;
                case "雨":
                    weatherData.put("url",local_url+"weather/雨.png");
                    weatherData.put("logo","icon-xiaoyu");
                case "小雨":
                    weatherData.put("url",local_url+"weather/雨.png");
                    weatherData.put("logo","icon-xiaoyu");
                case "中雨":
                    weatherData.put("url",local_url+"weather/雨.png");
                    weatherData.put("logo","icon-zhongyu");
                case "大雨":
                    weatherData.put("url",local_url+"weather/雨.png");
                    weatherData.put("logo","icon-dayu");
                case "雷阵雨":
                    weatherData.put("url",local_url+"weather/雨.png");
                    weatherData.put("logo","icon-leizhenyu");
                case "暴雨":
                    weatherData.put("url",local_url+"weather/雨.png");
                    weatherData.put("logo","icon-baoyu");
                case "雨夹雪":
                    weatherData.put("url",local_url+"weather/雨.png");
                    weatherData.put("logo","icon-yujiaxue");
                    break;
                case "雪":
                    weatherData.put("url",local_url+"weather/雪.png");
                    weatherData.put("logo","icon-xiaoxue");
                    break;
                case "小雪":
                    weatherData.put("url",local_url+"weather/雪.png");
                    weatherData.put("logo","icon-xiaoxue");
                    break;
                case "中雪":
                    weatherData.put("url",local_url+"weather/雪.png");
                    weatherData.put("logo","icon-zhongxue");
                    break;
                case "大雪":
                    weatherData.put("url",local_url+"weather/雪.png");
                    weatherData.put("logo","icon-daxue");
                    break;
                case "暴雪":
                    weatherData.put("url",local_url+"weather/雪.png");
                    weatherData.put("logo","icon-baoxue");
                    break;
                default:
                    weatherData.put("url",local_url+"weather/晴.png");
                    weatherData.put("logo","icon-qingtian");
                    break;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return weatherData;
    }

    @ApiOperation("返回全部人员信息")
    @GetMapping("/getAllUser")
    public CommonResult<List<Person>> getAllUser(){
        List<Person> allUser = geBaseUserService.getAllUser();
        CommonResult<List<Person>> result=new CommonResult<>();
        result.setCode(200);
        result.setData(allUser);
        return  result;
    }

    @GetMapping("/getPlace")
    @ApiOperation("输入提示地点")
    public JSONObject getPlace(String keyword) {
        JSONObject jsonObject = new JSONObject();
        try {
            // 创建URL对象并设置API的请求URL
            URL url = new URL("https://apis.map.qq.com/ws/place/v1/suggestion/?keyword="+keyword+"&key=VBTBZ-UPQCL-DQMPU-MVBKF-SXBFZ-26BHA");

            // 打开连接
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            // 设置请求方法
            connection.setRequestMethod("GET");

            // 获取输入流并读取数据
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            StringBuilder response = new StringBuilder();
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            reader.close();

            // 关闭连接
            connection.disconnect();

            // 处理JSON数据
            jsonObject = JSON.parseObject(response.toString());

        }catch (Exception e){
            e.printStackTrace();
        }
        return jsonObject;
    }
}
